#!/usr/bin/env python
import os, sys,mysql

files = os.listdir('./')



if len(sys.argv) <> 6 :
	print 'cl_stereo_load.py <path to scripts> <username> <password> <project> <initial> '
	sys.exit(1)

path = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
project = sys.argv[4]
initial = sys.argv[5]


#check db connection
conn=mysql.connect2server(password, username,'purchasable')  

cursor = conn.cursor ()

#check project
command = 'select unique_compounds, supplier_info_table, supplier_table from projects where project = "' + project + '"'
#print command
cursor.execute(command)
results=cursor.fetchall()
if len(results) == 0:
	print 'project does not exist'
	sys.exit(1)
conn.close()


clean_list = []
max_file_number = 0
#remove all none .smi from files
for i in files:
	
	if i[-4:] == '.smi':
		clean_list.append(i)

files = clean_list
files.sort()



for i in files:

	file_name = i[:-4] + '_start.bin'
	start_file = open(file_name, 'w')
	start_file.write("#BSUB-q short             	# Job queue\n#BSUB-o job.output              # output is sent to file job.output\n#BSUB-J test_mogon              # name of the job\n")

	start_file.write(path + '/stereoisomerizer.py ')
	start_file.write(i + ' ' + i[:-4] + '_stereo.smi False 3 > ' + i[:-4] + '_stereo.log\n')

	start_file.write(path + '/mysql_load_stereoisomers.py ')
	start_file.write(username + ' ' + password + ' ' +  i[:-4] + '_stereo.smi ' + project + ' ' + initial)


	start_file.close()
	os.system('chmod 744 '  + file_name)
	command = 'qsub -q long ' + file_name
	print command
	os.system(command)


	
	
